package com.szzg10.thinking.chapter18;

import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class Blips {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		
		System.out.println("Constructor---");
		Blip1 blip1 = new Blip1();
		Blip2 blip2 = new Blip2();
		System.out.println();
		
		System.out.println("Saving---");
		File file = new File(Worm.FILE_NAME_SERIALIZABLE);
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
		
		objectOutputStream.writeObject(blip1);
		objectOutputStream.writeObject(blip2);
		
		objectOutputStream.close();
		System.out.println();
		
		System.out.println("Recovering---");
		FileInputStream fileInputStream = new FileInputStream(file);
		ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
		blip1 = (Blip1)objectInputStream.readObject();
		
		objectInputStream.close();
	}
}

class Blip1 implements Externalizable {

	public Blip1() {
		System.out.println("Blip1 constructor!");
	}
	
	@Override
	public void readExternal(ObjectInput arg0) throws IOException,
			ClassNotFoundException {
		System.out.println("Blip1 readExternal!");
	}

	@Override
	public void writeExternal(ObjectOutput arg0) throws IOException {
		System.out.println("Blip1 writeExternal!");
	}
}

class Blip2 implements Externalizable {

	public Blip2() {
		System.out.println("Blip2 consturctor!");
	}
	
	@Override
	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		System.out.println("Blip2 readExternal!");
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		System.out.println("Blip2 writeExternal!");
	}
	
}
